#include <stdio.h>
#include <vector>
#include "CServerList.h"
#include "CDirectories.h"
#include "Utils.h"

#pragma warning(disable:4996)

static std::vector<LPSERVER> g_ServerList;

CServerList::CServerList()
{ }

BOOL CServerList::Initialize(void)
{
	BOOL			bRet				= TRUE		;
	FILE*			fp								;
	CDirectories	dirs							;
	char			szFile[MAX_PATH]	= {0x00}	,
					szBuffer[1024]		= {0x00}	;
	LPSERVER		lpNew							;
	size_t			n								,
					x								;

	strcpy(szFile, dirs.GetWLDirectory());
	strcat(szFile, "\\SERVER.INI");

	fp = fopen(szFile, "rb");

	if((bRet = (NULL != fp))) {
		while(fgets(szBuffer, 1024, fp)) {
			if(strstr(szBuffer, "*")) {
				for(n = 0; n < strlen(szBuffer); ++n) {
					if('\r' == szBuffer[n] || '\n' == szBuffer[n]) {
						szBuffer[n] = 0x00;
					} else if('*' == szBuffer[n])
						x = n;
				}

				szBuffer[x] = 0x00;

				if(strcmp(szBuffer, "Name") != 0) {
					lpNew				= new SERVER;
					lpNew->lpszName		= StringDuplicate(szBuffer);
					lpNew->lpszAddr		= StringDuplicate(szBuffer + strlen(szBuffer) + 1);
					g_ServerList.push_back(lpNew);
				}
			}
			memset(szBuffer, 0, sizeof(char) * 1024);
		}
		fclose(fp);
	}

	return bRet;
}

LPSERVER CServerList::GetNext(LPSERVER lpCurrent)
{
	LPSERVER						lpRet	=	NULL	;
	BOOL							bNext	=	FALSE	;
	std::vector<LPSERVER>::iterator it					;

	if(!lpCurrent && (g_ServerList.begin() != g_ServerList.end())){
		lpRet = *g_ServerList.begin();
	} else {
		for(it = g_ServerList.begin();
			it != g_ServerList.end(); 
			++it)
		{
			if(bNext) {
				lpRet = *it;
				break;
			}

			if(lpCurrent == *it)
				bNext = TRUE;
		}
	}

	return lpRet;
}

void CServerList::Uninitialize(void)
{
	std::vector<LPSERVER>::iterator it;
	for(it = g_ServerList.begin();
		it != g_ServerList.end();
		++it)
	{
		delete[] (*it)->lpszAddr;
		delete[] (*it)->lpszName;
		delete *it;
	}

	g_ServerList.clear();
}

CServerList::~CServerList()
{ }
